﻿using NPoco;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using YYBlog.Core.Entity;
using NPoco.Expressions;

namespace YYBlog.Core.Commands.Accounts
{
    public class LoginCommand
    {
        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        public string ReturnUrl { get; set; }
    }

    public class LoginCommandResult : CommandResult
    {
        public LoginCommandResult()
            : base()
        { }

        public LoginCommandResult(string trrorMessage)
            : base(trrorMessage)
        { }

        public Author Author { get; set; }
    }

    public class LoginCommandInvoker : ICommandInvoker<LoginCommand, LoginCommandResult>
    {
        private readonly Database _db;

        public LoginCommandInvoker(Database db)
        {
            _db = db;
        }

        public LoginCommandResult Execute(LoginCommand loginCommand)
        {
            var hashedPassword = Hasher.GetMd5Hash(loginCommand.Password);
         
            var author = _db.FirstOrDefault<Author>(" WHERE Email=@0 AND Password=@1", loginCommand.Email, hashedPassword);
            if (author != null)
                return new LoginCommandResult() { Author = author };

            return new LoginCommandResult(trrorMessage: "用户名或密码不正确") { };
        }
    }
}